import store from '@/conf/store/index'
import router from '@/conf/router'
import http from '@/conf/axios/index'

/**
 * 判断权限
 * @param permission
 */
export function authority(permission: []) {
    let permissionArray = JSON.parse(store.getters.permission);
    let b = false;
    if (permission.length > 0) {
        for (let i = 0; i < permission.length; i++) {
            if (permissionArray.indexOf(permission[i]) > -1) {
                b = true;
                break;
            }
        }
    }
    return b;
}

/**
 * 菜单uri 路径
 * @param item
 */
export function menuLinkPath(item: any) {
    let routerPath = ("/" + (item['scope'] + item['router']).replaceAll("//", "/")).toLowerCase();
    return routerPath;
}

/**
 * 添加路由
 * @param item
 */
export function addRoute(item: any) {
    if (item['component']) {
        let requireComponents: object = import.meta.glob("@/views/**/*.vue");
        Object.keys(requireComponents).filter((fileName: string) => {
            if (fileName.indexOf(item['component']) != -1) {
                return true;
            }
            return false;
        }).map(fileName => {
            // @ts-ignore
            let views = requireComponents[fileName];
            let routerPath = menuLinkPath(item);
            let routerLink = {name: '', path: '', component: {}};
            routerLink['name'] = routerPath;
            routerLink['path'] = routerPath;
            routerLink['component'] = views;
            let parentName = item['scope'];
            if (item['routerType'] === 'sub_route') {
                parentName = item['parentName'];
            }
            router.addRoute(parentName, routerLink);
        });
    }
}

/**
 * 普通跳转
 * @param path
 */
export function pageGo(path: string) {
    router.push(path)
}

//大屏跳转
export function screenPageLink(item: any) {
    let routerPath = item.path;
    if (item.path && item.path.indexOf('http') === -1) {
        routerPath = "/#" + item.path;
        if (item.screenType === 'other') {
            routerPath = item.path;
        }
    }
    window.open(routerPath, item.screenRouterType); //打开新标签
}

//退出方法
export function logout(item: any) {
    http.logout().then((response: any) => {
        // @ts-ignore
        store.dispatch("logout", true).then(r => {
            router.push("/login")
        });
    });
}